<?php
// 修复路径问题 - 使用绝对路径
$adminDir = __DIR__;
$projectRoot = dirname($adminDir);

require_once $projectRoot . '/config/config.php';
require_once $projectRoot . '/includes/auth.php';
require_once $projectRoot . '/includes/database.php';

// session已由config/config.php统一管理，无需重复调用

// 检查登��状态
requireLogin();

// 简单的重定向函数
function redirect($url) {
    header("Location: " . $url);
    exit;
}

// 初始化数据库
$db = new Database();

// 获取系统设置（包含动态标题）
$settings = $db->getSettings();
$siteTitle = $settings['site_title'] ?? SITE_TITLE;

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add') {
        $data = [
            'category_id' => (int)$_POST['category_id'],
            'name_en' => sanitizeInput($_POST['name_en']),
            'name_cn' => sanitizeInput($_POST['name_cn']),
            'sort' => (int)$_POST['sort']
        ];

        if ($db->addTag($data)) {
            $_SESSION['success_message'] = '标签添加成功！';
        } else {
            $_SESSION['error_message'] = '标签添加失败！可能是英文名称在同级分类下已重复或分类不存在。';
        }
        redirect(getUrl('admin/tags'));
    } elseif ($action === 'edit') {
        $id = (int)$_POST['id'];
        $data = [
            'category_id' => (int)$_POST['category_id'],
            'name_en' => sanitizeInput($_POST['name_en']),
            'name_cn' => sanitizeInput($_POST['name_cn']),
            'sort' => (int)$_POST['sort']
        ];

        if ($db->updateTag($id, $data)) {
            $_SESSION['success_message'] = '标签更新成功！';
        } else {
            $_SESSION['error_message'] = '标签更新失败！可能是英文名称在同级分类下已重复或分类不存在。';
        }
        redirect(getUrl('admin/tags'));
    } elseif ($action === 'delete') {
        $id = (int)$_POST['id'];
        if ($db->deleteTag($id)) {
            $_SESSION['success_message'] = '标签删除成功！';
        } else {
            $_SESSION['error_message'] = '标签删除失败！';
        }
        redirect(getUrl('admin/tags'));
    }
}

// 获取并清除消息
$success_message = $_SESSION['success_message'] ?? null;
unset($_SESSION['success_message']);

$error_message = $_SESSION['error_message'] ?? null;
unset($_SESSION['error_message']);

// 获取标签列表和分类列表
$tags = $db->getTags();
$categories = $db->getCategories();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>标签管理 - <?php echo $siteTitle; ?></title>

    <!-- 样式文件 -->
    <link rel="stylesheet" href="<?php echo asset('css/admin.css'); ?>">
    <link rel="stylesheet" href="<?php echo asset('libs/fontawesome/all.min.css'); ?>">

    <!-- 网站图标 -->
    <link rel="icon" type="image/x-icon" href="<?php echo asset('images/favicon.ico'); ?>">
</head>
<body class="admin-page">
    <!-- 侧边栏 -->
    <aside class="sidebar">
        <div class="sidebar-header">
            <div class="logo">
                <i class="fas fa-compass"></i>
                <h2><?php echo $siteTitle; ?></h2>
            </div>
        </div>

        <nav class="sidebar-nav">
            <ul>
                <li>
                    <a href="<?php echo getUrl('admin/'); ?>">
                        <i class="fas fa-tachometer-alt"></i>
                        <span>仪表盘</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo getUrl('admin/navigations'); ?>">
                        <i class="fas fa-link"></i>
                        <span>导航管理</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo getUrl('admin/categories'); ?>">
                        <i class="fas fa-folder"></i>
                        <span>分类管理</span>
                    </a>
                </li>
                <li class="active">
                    <a href="<?php echo getUrl('admin/tags'); ?>">
                        <i class="fas fa-tags"></i>
                        <span>标签管理</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo getUrl('admin/settings'); ?>">
                        <i class="fas fa-cog"></i>
                        <span>系统设置</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo getUrl(); ?>" target="_blank">
                        <i class="fas fa-external-link-alt"></i>
                        <span>访问前台</span>
                    </a>
                </li>
            </ul>
        </nav>

        <div class="sidebar-footer">
            <div class="user-info">
                <i class="fas fa-user-circle"></i>
                <span><?php echo $_SESSION['admin_username'] ?? 'Admin'; ?></span>
            </div>
            <a href="<?php echo getUrl('admin/index.php?action=logout'); ?>" class="logout-btn" title="退出登录">
                <i class="fas fa-sign-out-alt"></i>
            </a>
        </div>
    </aside>

    <!-- 主要内容区域 -->
    <main class="main-content">
        <!-- 顶部栏 -->
        <header class="content-header">
            <div class="header-left">
                <h1><i class="fas fa-tags"></i> 标签管理</h1>
                <p>管理导航标签，作为分类的子级，支持创建、编辑和删除操作。</p>
            </div>
            <div class="header-right">
                <button class="btn btn-primary" onclick="showAddModal()">
                    <i class="fas fa-plus"></i> 添加标签
                </button>
            </div>
        </header>

        <!-- 消息提示 -->
        <?php if (isset($success_message)): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                <?php echo $success_message; ?>
            </div>
        <?php endif; ?>

        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle"></i>
                <?php echo $error_message; ?>
            </div>
        <?php endif; ?>

        <!-- 标签列表 -->
        <section class="content-section">
            <div class="card">
                <div class="card-header">
                    <h3><i class="fas fa-list"></i> 标签列表</h3>
                    <p>共 <?php echo count($tags); ?> 个标签</p>
                </div>
                <div class="card-body">
                    <?php if (!empty($tags)): ?>
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>所属分类</th>
                                        <th>英文名称</th>
                                        <th>中文名称</th>
                                        <th>排序</th>
                                        <th>创建时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($tags as $tag): ?>
                                        <?php
                                        // 获取所属分类名称
                                        $categoryName = '未知分类';
                                        foreach ($categories as $category) {
                                            if ($category['id'] == $tag['category_id']) {
                                                $categoryName = $category['name'];
                                                break;
                                            }
                                        }
                                        ?>
                                        <tr>
                                            <td><?php echo $tag['id']; ?></td>
                                            <td><?php echo htmlspecialchars($categoryName); ?></td>
                                            <td><?php echo htmlspecialchars($tag['name_en']); ?></td>
                                            <td><?php echo htmlspecialchars($tag['name_cn']); ?></td>
                                            <td><?php echo $tag['sort']; ?></td>
                                            <td><?php echo $tag['created_at']; ?></td>
                                            <td>
                                                <div class="btn-group">
                                                    <button class="btn btn-sm btn-outline-primary"
                                                            onclick="editTag(<?php echo htmlspecialchars(json_encode($tag)); ?>)">
                                                        <i class="fas fa-edit"></i> 编辑
                                                    </button>
                                                    <button class="btn btn-sm btn-outline-danger"
                                                            onclick="deleteTag(<?php echo $tag['id']; ?>, '<?php echo htmlspecialchars($tag['name_cn']); ?>')">
                                                        <i class="fas fa-trash"></i> 删除
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <i class="fas fa-tags"></i>
                            <h3>暂无标签</h3>
                            <p>还没有创建任何标签，点击上方按钮开始添加。</p>
                            <button class="btn btn-primary" onclick="showAddModal()">
                                <i class="fas fa-plus"></i> 添加第一个标签
                            </button>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </section>
    </main>

    <!-- 添加/编辑标签模态框 -->
    <div id="tagModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">添加标签</h3>
                <button class="close-btn" onclick="closeModal()">&times;</button>
            </div>
            <form method="POST" class="modal-body">
                <input type="hidden" name="action" id="formAction" value="add">
                <input type="hidden" name="id" id="tagId">

                <div class="form-group">
                    <label for="category_id">所属分类 *</label>
                    <select id="category_id" name="category_id" required>
                        <option value="">请选择分类</option>
                        <?php foreach ($categories as $category): ?>
                            <option value="<?php echo $category['id']; ?>">
                                <?php echo htmlspecialchars($category['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="form-group">
                    <label for="name_en">英文名称 *</label>
                    <input type="text" id="name_en" name="name_en" required
                           placeholder="请输入英文名称，用于URL和标识"
                           pattern="[a-z0-9_-]+" title="只能包含小写字母、数字、下划线和横线">
                    <small class="form-text">只能包含小写字母、数字、下划线和横线，用于URL和标识</small>
                </div>

                <div class="form-group">
                    <label for="name_cn">中文名称 *</label>
                    <input type="text" id="name_cn" name="name_cn" required
                           placeholder="请输入中文名称，用于显示">
                    <small class="form-text">用于前台显示的中文名称</small>
                </div>

                <div class="form-group">
                    <label for="sort">排序序号 *</label>
                    <input type="number" id="sort" name="sort" required
                           placeholder="数字越小排序越靠前" min="1">
                    <small class="form-text">数字越小排序越靠前</small>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> 保存
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- 删除确认模态框 -->
    <div id="deleteModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>确认删除</h3>
                <button class="close-btn" onclick="closeDeleteModal()">&times;</button>
            </div>
            <div class="modal-body">
                <p>确定要删除标签 "<span id="deleteTagName"></span>" 吗？</p>
                <p class="text-danger">注意：删除后不可恢复！</p>
                <form method="POST" style="display: none;" id="deleteForm">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" id="deleteTagId">
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeDeleteModal()">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmDelete()">
                    <i class="fas fa-trash"></i> 确认删除
                </button>
            </div>
        </div>
    </div>

    <script>
        // 显示添加模态框
        function showAddModal() {
            document.getElementById('modalTitle').textContent = '添加标签';
            document.getElementById('formAction').value = 'add';
            document.getElementById('tagId').value = '';
            document.getElementById('category_id').value = '';
            document.getElementById('name_en').value = '';
            document.getElementById('name_cn').value = '';
            document.getElementById('sort').value = '';
            document.getElementById('tagModal').classList.add('show');
        }

        // 编辑标签
        function editTag(tag) {
            document.getElementById('modalTitle').textContent = '编辑标签';
            document.getElementById('formAction').value = 'edit';
            document.getElementById('tagId').value = tag.id;
            document.getElementById('category_id').value = tag.category_id;
            document.getElementById('name_en').value = tag.name_en;
            document.getElementById('name_cn').value = tag.name_cn;
            document.getElementById('sort').value = tag.sort;
            document.getElementById('tagModal').classList.add('show');
        }

        // 删除标签
        function deleteTag(id, name) {
            document.getElementById('deleteTagId').value = id;
            document.getElementById('deleteTagName').textContent = name;
            document.getElementById('deleteModal').classList.add('show');
        }

        // 确认删除
        function confirmDelete() {
            document.getElementById('deleteForm').submit();
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('tagModal').classList.remove('show');
        }

        function closeDeleteModal() {
            document.getElementById('deleteModal').classList.remove('show');
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('tagModal');
            const deleteModal = document.getElementById('deleteModal');
            if (event.target === modal) {
                closeModal();
            }
            if (event.target === deleteModal) {
                closeDeleteModal();
            }
        }
    </script>
</body>
</html>